<?php

namespace app\backend\controller;

use app\common\model\Topics;
use think\Controller;
use think\Request;

class Topic extends Controller
{
    //专题列表
    public function index()
    {
        //
        $topics=Topics::withTrashed()->select();

        $this->assign(compact('topics'));
        return $this->fetch();
    }

    //添加专题
    public function create(Request $request)
    {
        if($request->isGet()) {
            $topic_opera = '添加';
            $this->assign(compact('topic_opera'));
            return $this->fetch();
        }

        $title=$request->post('title','','trim,strip_tags');

        //验证
        $err_msg=$this->validate($request->post('','','trim,strip_tags'),[
            'title'=>'require|max:20|unique:topics|token'
        ]);

        if($err_msg !==true){
            return renderJs($err_msg);
        }

        //写入数据库
        $topic=new Topics();
        $topic->title=$title;
        $topic->save();

        return renderJs('写入成功','/admin/topics');
    }

    //操作 => 删除,恢复 [软删除]
    public function opt(Request $request)
    {
        $id=$request->post('id',0,'trim,strip_tags,intval');
        $opt=$request->post('opt','','trim,strip_tags');
        //验证是否存在此条专题
        $topic_info=Topics::withTrashed()->where('id',$id)->find();

        if(!$topic_info){
            return json(['msg'=>'非法操作','code'=>-1]);
        }

        //操作
        $opt_res='';
        switch($opt){
            case 'delete':
                $opt_res='删除';
                $topic_info->delete();
                break;
            case 'recover':
                $opt_res='恢复';
                $topic_info->restore();
                break;
            default:
                return json(['msg'=>'非法操作','code'=>-1]);
        }

        return json(['msg'=>$opt_res.'操作成功','code'=>200]);
    }

    //修改专题
    public function update($id,Request $request)
    {
        $topic_info = Topics::get($id);
        if (!$topic_info) {
            return renderJs('不存在的数据');
        }

        if($request->isGet()) {
            $topic_opera = '修改';
            //查询修改数据是否存在

            $this->assign(compact('topic_opera', 'topic_info'));
            return $this->fetch('create');
        }


        //获取请求信息
        $title=$request->post('title','','trim,strip_tags');

        //验证
        $err_msg=$this->validate($request->post('','','trim,strip_tags'),[
            'title'=>'require|max:20|unique:topics|token'
        ],[
            'title.require'=>'请填写专题名',
            'title.max'=>'专题名最大20个字符',
            'title.unique'=>'专题名已存在'
        ]);
        if($err_msg !==true){
            return renderJs($err_msg);
        }

        //写入数据库
        $topic_info->title=$title;
        $topic_info->save();

        return renderJs('写入成功','/admin/topics');
    }

    //恢复删除方法
    public function recover()
    {

    }
}
